﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.Components;
using Aliyeye.Car.Net.UI.Common;
using Aliyeye.Car.Net.UI.PrintExport;
using Aliyeye.Car.Net.UI.PopupDialog;
using Aliyeye.Car.Net.UI.SystemHelp;

namespace Aliyeye.Car.Net.UI.OrderModel
{
    /// <summary>
    /// 短租自驾
    /// </summary>
    public partial class AllOrdersList : Aliyeye.Car.Net.UI.BaseForm
    {
        private string strSearch = string.Empty;

        public AllOrdersList()
        {
            InitializeComponent();
            DateTime dtNow = DateTime.Now;
            DateTime dt = new DateTime(dtNow.Year, dtNow.Month, 1);

            dtpBookTime.Value = dt;
            dtpEndBooktime.Value = dtNow;

            if (Login.RoleName.Trim() == "系统管理员")
            {
                DeleteOrder.Visible = true;
            }
        }

        private void ShortLeaseWithDriverList_Load(object sender, EventArgs e)
        {
            BindComboBoxInfo();
            GetSearchString();
            this.pager1.PageCurrent = 1;
            this.pager1.Bind();
        }

        private void BindComboBoxInfo()
        {
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ArchivesSvc.SoapHeaderClass sopaHeader = new ArchivesSvc.SoapHeaderClass();

            DataSet dsBrand = null;
            ServiceManipulator.SafeAsyncExecution<ArchivesSvc.ArchivesServiceSoapClient>(
                proxy => proxy.ComBoxBrand(sopaHeader),
                result =>
                {
                    if (result.Error == null)
                    {
                        dsBrand = (DataSet)result.Result;

                        DataRow dr = dsBrand.Tables[0].NewRow();
                        dr["Id"] = "-1";
                        dr["Name"] = "全部";
                        dr["Namevalue"] = "全部";
                        dsBrand.Tables[0].Rows.Add(dr);

                        DataView dv = dsBrand.Tables[0].DefaultView;
                        dv.Sort = "id asc";

                        cmbBrand.DisplayMember = "Namevalue";
                        cmbBrand.ValueMember = "Id";
                        cmbBrand.DataSource = dv;
                        cmbBrand.SelectedIndex = 0;
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        private int dgvBind()
        {
            string _strSql = "1=1 ";
            string strWhere = strSearch;
            PageData pageData = new PageData(this, pager1, overlay);
            pageData.TableName = "Reserve left join Customer on Customer.Id=Reserve.CustId left join Car on Car.Id=Reserve.CarId left join Accounts_Users on Accounts_Users.UserID=Car.UserId  left join Accounts_Users InputUser on InputUser.UserID=Reserve.UserId left join Accounts_Roles on Accounts_Roles.RoleID=InputUser.RoleId";
            pageData.PrimaryKey = "Reserve.Id";
            pageData.OrderStr = "Reserve.InpuTime desc";
            pageData.PageIndex = this.pager1.PageCurrent;
            pageData.PageSize = this.pager1.PageSize;
            pageData.QueryCondition = _strSql + strWhere.ToString();
            pageData.QueryFieldName = "Reserve.InpuTime,Reserve.Id,Reserve.Type, Reserve.BookTime ,Reserve.OrderSataus, Reserve.EndBooktime , Customer.Code as CustomerCode,Customer.Name,  Car.Code,Brand,Car.Cartype,ExhaustVolume,DayRent,Color,InsureEnd,OvertimePrie,DayLimitKM,TimeoutPrie,Accounts_Users.TrueName,InputUser.TrueName as inputUserName,Accounts_Roles.Description,(select Count(*)  from Illegal where Illegal.CarCode=Car.Code and Reserve.BookTime<=Illegal.Time and Illegal.Time<=Reserve.EndBooktime) as IllegalCount";

            DataSet ds = pageData.QueryDataTable();
            dgvInfo.AutoGenerateColumns = false;
            dgvInfo.DataSource = this.pager1.bindingSource;
            return pageData.TotalCount;
        }

        private void ExportAllSearchCondistion()
        {
            string _strSql = "1=1 ";
            string strWhere = strSearch;
            string strOrderBy = " order by Reserve.InpuTime desc";
            string strSelect = "select Reserve.InpuTime, Reserve.Id,Reserve.Type, Reserve.BookTime ,Reserve.OrderSataus, Reserve.EndBooktime , Customer.Code as CustomerCode,Customer.Name,  Car.Code,Brand,Car.Cartype,ExhaustVolume,DayRent,Color,InsureEnd,OvertimePrie,DayLimitKM,TimeoutPrie,Accounts_Users.TrueName,InputUser.TrueName as inputUserName,Accounts_Roles.Description from Reserve left join Customer on Customer.Id=Reserve.CustId left join Car on Car.Id=Reserve.CarId left join Accounts_Users on Accounts_Users.UserID=Car.UserId  left join Accounts_Users InputUser on InputUser.UserID=Reserve.UserId left join Accounts_Roles on Accounts_Roles.RoleID=InputUser.RoleId";
            string strSql = strSelect + " where " + _strSql + strWhere.ToString() + strOrderBy;

            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            CarSvc.SoapHeaderClass sopaHeader = new CarSvc.SoapHeaderClass();

            DataSet dsCars = null;
            ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
                proxy => proxy.GetAllListForSearchCondistion(sopaHeader, strSql),
                result =>
                {
                    if (result.Error == null)
                    {
                        dsCars = (DataSet)result.Result;
                        //开始导出
                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            string filePath = saveFileDialog.FileName;
                            ExcelHelper excelHelper = new ExcelHelper();
                            string msg = "";
                            if (excelHelper.AllOrderListExport(dsCars, filePath, ref msg))
                            {
                                PageCommon.Notify("文档导出成功！");
                                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                            }
                            else
                            {
                                PageCommon.Alert(msg);
                                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                            }
                        }
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message);
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        private int pager1_EventPaging(EventPagingArg e)
        {
            return dgvBind();
        }

        private void dgvInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (IsANonHeaderButtonCell(e))
            {
                ButtonClicked(e);
            }
            if (IsANonHeaderLinkButtonCell(e))
            {
                LinkButtonClicked(e);
            }
        }

        private void ButtonClicked(DataGridViewCellEventArgs e)
        {
            String strButtonContent = dgvInfo.Columns[e.ColumnIndex].Name;
            String id = dgvInfo.Rows[e.RowIndex].Cells["ReserveID"].Value.ToString();
            
            if (strButtonContent.Trim().Equals("查看"))
            {
                OrderInfoView userForm = new OrderInfoView(id);
                userForm.ShowDialog();
            }

            if (strButtonContent.Trim().Equals("DeleteOrder"))
            {
                //"确定删除？"
                string status = dgvInfo.Rows[e.RowIndex].Cells["状态"].Value.ToString();
                if (status.ToLower().Trim() == "true")
                {
                    PageCommon.Alert("此单已结算，不能删除！");
                    return;
                }
                DialogConfirm diaSecc = new DialogConfirm("删除后，无法恢复，确定删除吗？");
                if (diaSecc.ShowDialog() == DialogResult.OK)
                {
                    overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
                    ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();

                    ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
                   proxy => proxy.Delete(sopaHeaderReserveSvc, Convert.ToInt32(id)),
                   result =>
                   {
                       if (result.Error == null)
                       {
                           PageCommon.Notify("删除信息成功！");
                           overlay.FadeOut(); Cursor.Current = Cursors.Default;
                       }
                       else
                       {
                           PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                       }
                   },
                   this
               );
                }
            }

            this.pager1.Bind();
        }

        private void LinkButtonClicked(DataGridViewCellEventArgs e)
        {
            String strButtonContent = dgvInfo.Columns[e.ColumnIndex].Name;
            int id = Convert.ToInt32(dgvInfo.Rows[e.RowIndex].Cells["ReserveID"].Value.ToString());
            String count = dgvInfo.Rows[e.RowIndex].Cells["罚单"].Value.ToString();
            if (count.Trim() == "0")
                return;
            if (strButtonContent.Trim().Equals("罚单"))
            {
                IllegalList userForm = new IllegalList(id);
                userForm.ShowDialog();
            }
            //this.pager1.Bind();
        }

        private bool IsANonHeaderButtonCell(DataGridViewCellEventArgs cellEvent)
        {
            if (dgvInfo.Columns[cellEvent.ColumnIndex] is
                 DataGridViewButtonColumn &&
                 cellEvent.RowIndex != -1)
            { return true; }
            else { return (false); }
        }

        private bool IsANonHeaderLinkButtonCell(DataGridViewCellEventArgs cellEvent)
        {
            if (dgvInfo.Columns[cellEvent.ColumnIndex] is
                 DataGridViewLinkColumn &&
                 cellEvent.RowIndex != -1)
            { return true; }
            else { return (false); }
        }

        //搜索
        private void btnSearch_Click(object sender, EventArgs e)
        {
            GetSearchString();
            this.pager1.Bind();
        }

        private void GetSearchString()
        {
            string strWhere2 = "";
            if (cmbBrand.Text.Trim() != "全部" && !string.IsNullOrEmpty(cmbBrand.Text))
            {
                strWhere2 = " And Brand= '" + cmbBrand.Text + "'";
            }
            if (!string.IsNullOrEmpty(txtCarCode.Text))
            {
                strWhere2 += " And  Car.Code like '%" + txtCarCode.Text + "%'";
            }

            if (!string.IsNullOrEmpty(txtCustomName.Text))
            {
                strWhere2 += " And  Customer.Name like '%" + txtCustomName.Text + "%'";
            }

            string strBeginDate = dtpBookTime.Value.ToString("yyyy-MM-dd");
            string strEndDate = dtpEndBooktime.Value.ToString("yyyy-MM-dd");

            strWhere2 += " and datediff(dd, BookTime ,'" + strBeginDate + "') <= 0 ";
            strWhere2 += " and datediff(dd, EndBooktime ,'" + strEndDate + "') >= 0 ";

            strSearch = strWhere2;
        }

        //全部
        private void btnAll_Click(object sender, EventArgs e)
        {
            strSearch = "";
            txtCarCode.Text = "";
            txtCustomName.Text = "";

            this.pager1.Bind();
        }

        private void dgvInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvInfo.Rows.Count; )
                {
                    this.dgvInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void dgvInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;
            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "状态")
            {
                if (e.Value != null)
                {
                    if (Convert.ToBoolean(e.Value))
                    {
                        e.Value = "已结算";
                    }
                    else
                    {
                        e.Value = "未结算";
                    }
                }
            }

            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "订车类型")
            {
                if (e.Value != null)
                {
                    if (Convert.ToInt32(e.Value) == 1)
                    {
                        e.Value = "长租自驾";
                        //this.dgvInfo.Rows[e.RowIndex].Cells["租赁时间"].Value = time.ToString() + " 月";
                    }

                    else if (Convert.ToInt32(e.Value) == 2)
                    {
                        e.Value = "短租自驾";
                        //this.dgvInfo.Rows[e.RowIndex].Cells["租赁时间"].Value = time.ToString() + " 小时";
                    }
                    else if (Convert.ToInt32(e.Value) == 3)
                    {
                        e.Value = "长租带驾";
                        //this.dgvInfo.Rows[e.RowIndex].Cells["租赁时间"].Value = time.ToString() + " 月";
                    }
                    else if (Convert.ToInt32(e.Value) == 4)
                    {
                        e.Value = "短租带驾";
                        //this.dgvInfo.Rows[e.RowIndex].Cells["租赁时间"].Value = time.ToString() + " 小时";
                    }
                }
            }

            //if (this.dgvInfo.Columns[e.ColumnIndex].Name == "分店部门")
            //{
            //    if (e.Value != null)
            //    {
            //        e.Value = GetDepartmentName(Convert.ToInt32(e.Value));
            //    }
            //}

            //if (this.dgvInfo.Columns[e.ColumnIndex].Name == "职称")
            //{
            //    if (e.Value != null)
            //    {
            //        e.Value = GetRoleName(Convert.ToInt32(e.Value));
            //    }
            //}
        }

        //导出
        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportAllSearchCondistion();
        }

        #region 车牌号 输入框数据绑定

        string driverName = string.Empty;
        private void txtCarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string strSearch = this.txtCarCode.Text;
                if (string.IsNullOrEmpty(strSearch))
                {
                    DialogWarning dia = new DialogWarning("车牌号不能为空！");
                    dia.ShowDialog();
                    return;
                }
                else
                {
                    DisplayCarLIst(strSearch, "车牌号");
                }
            }
        }

        private void DisplayCarLIst(string strSearch, string type)
        {
            if (string.IsNullOrEmpty(strSearch))
            {
                return;
            }
            string strSelectWhere = "";
            if (type == "车牌号")
            {
                strSelectWhere = " Code like '%" + strSearch + "%'";
            }
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            DataSet ds = null;
            this.dgvDriverInfo.DataSource = null;
            dgvDriverInfo.AutoGenerateColumns = false;
            CarSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.CarSvc.SoapHeaderClass();
            ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
                proxy => proxy.GetList(sopaHeader, strSelectWhere),
                result =>
                {
                    if (result.Error == null)
                    {
                        ds = (DataSet)result.Result;
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            dgvDriverInfo.DataSource = ds.Tables[0];
                            this.dgvDriverInfo.Visible = true;
                            this.dgvDriverInfo.Focus();
                        }
                        else
                        {
                            PageCommon.Alert("查找的车辆不存在，请重新查询！");
                            txtCarCode.Text = driverName;
                        }
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        private void dgvDriveInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvDriverInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvDriverInfo.Rows.Count; )
                {
                    this.dgvDriverInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void dgvDriverInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                this.txtCarCode.Text = this.dgvDriverInfo.CurrentRow.Cells["车牌号1"].Value.ToString();
                //  driverID = Convert.ToInt32(this.dgvInfo.CurrentRow.Cells["编号"].Value.ToString());
                driverName = this.txtCarCode.Text;
                this.dgvDriverInfo.Visible = false;
                this.txtCustomName.Focus();
            }
        }

        private void dgvDriverInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;
            if (this.dgvDriverInfo.Columns[e.ColumnIndex].Name == "性别")
            {
                if (e.Value != null)
                {
                    if (Convert.ToBoolean(e.Value))
                    {
                        e.Value = "带驾";
                    }
                    else
                    {
                        e.Value = "自驾";
                    }
                }
            }
        }

        #endregion 车牌号 输入框数据绑定

        # region 选择客户

        private void dgvCustomerInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;

            if (this.dgvCustomerInfo.Columns[e.ColumnIndex].Name == "客户类型")
            {
                if (e.Value != null)
                {
                    if (e.Value.ToString().Trim() == "1")
                    {
                        e.Value = "个体户客户";
                    }
                    else
                    {
                        e.Value = "企业客户";
                    }
                }
            }
        }

        private void dgvCustomerInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvCustomerInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvCustomerInfo.Rows.Count; )
                {
                    this.dgvCustomerInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        string customerName = "";

        private void dgvCustomerInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                this.txtCustomName.Text = this.dgvCustomerInfo.CurrentRow.Cells["姓名"].Value.ToString();
                customerName = this.txtCustomName.Text;
                this.dgvCustomerInfo.Visible = false;
            }
        }

        private void txtCustomName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string strSearch = txtCustomName.Text;
                if (string.IsNullOrEmpty(strSearch))
                {
                    DialogWarning dia = new DialogWarning("客户名不能为空！");
                    dia.ShowDialog();
                    return;
                }
                else
                {
                    DisplayCustomeLIst(strSearch, "姓名");
                }
            }
        }

        private void DisplayCustomeLIst(string strSearch, string type)
        {
            if (string.IsNullOrEmpty(strSearch))
            {
                return;
            }

            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            string strSelectWhere = "";
            if (type == "姓名")
            {
                strSelectWhere = " Name like '%" + strSearch + "%'";
            }
            if (type == "客户编号")
            {
                strSelectWhere = " Code like '%" + strSearch + "%'";
            }
            DataSet ds = null;
            dgvCustomerInfo.DataSource = null;
            dgvCustomerInfo.AutoGenerateColumns = false;

            CustomerSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.CustomerSvc.SoapHeaderClass();
            ServiceManipulator.SafeAsyncExecution<CustomerSvc.CustomerServiceSoapClient>(
                proxy => proxy.GetList(sopaHeader, strSelectWhere),
                result =>
                {
                    if (result.Error == null)
                    {
                        ds = (DataSet)result.Result;
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            dgvCustomerInfo.DataSource = ds.Tables[0];
                            this.dgvCustomerInfo.Visible = true;
                            this.dgvCustomerInfo.Focus();
                        }
                        else
                        {
                            //txtcustcode.Text = customerCode;
                            txtCustomName.Text = customerName;
                            PageCommon.Alert("查找的客户不存在，请重新查找！");
                        }
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message);
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

        }
        #endregion
    }
}
